import {renderer, VIEW_WIDTH, VIEW_HEIGHT, stageManager, TextureGenerator, TilingSprite, getAnchors} from "./common";
import {current_stage as l_stage} from "./loader";
import {current_stage as fb_stage} from "./free-battlefield";

stageManager.add(l_stage, fb_stage)


if (location.hash === "#nav") {
    stageManager.set(fb_stage);
} else if (location.hash === "#lights") {
    var stage = new PIXI.Container(),
        light = new PIXI.lights.PointLight(0xffffff, 2);
    stage["__id"] = "QAQ"
    debugger
    PIXI.loader
        .add('bg_diffuse', '/images/bg68.jpg')
        .add('bg_normal', '/images/bg68_normal.jpg')
        .load(function (loader, res) {
            // var bg = new PIXI.Sprite(res.bg_diffuse.texture);

            var unit_normal_tex = <PIXI.Texture>res.bg_normal.texture;
            var full_normal_tex = TextureGenerator(renderer, stage, unit_normal_tex, VIEW_WIDTH, VIEW_HEIGHT, { y: -5 });

            var unit_diffuse_tex = <PIXI.Texture>res.bg_diffuse.texture;
            var full_diffuse_tex = TextureGenerator(renderer, stage, unit_diffuse_tex, VIEW_WIDTH, VIEW_HEIGHT, { y: -5 });

            var bg = new PIXI.extras.TilingSprite(full_diffuse_tex, VIEW_WIDTH, VIEW_HEIGHT);
            bg["normalTexture"] = full_normal_tex;
            // bg.alpha = 0.2
            // stage.addChild(bg);

            // var bg2 = new PIXI.Sprite(full_diffuse_tex);
            // bg2.alpha = 0.5
            // stage.addChild(bg2);


            // var bg3 = new PIXI.Sprite(full_normal_tex);
            // bg3.alpha = 0.5
            // stage.addChild(bg3);

            // var bg4 = new PIXI.Sprite(full_diffuse_tex);
            // bg4["normalTexture"] = full_normal_tex;
            // stage.addChild(bg4);

            var bg5 = new TilingSprite(unit_diffuse_tex, VIEW_WIDTH, VIEW_HEIGHT, null, null, { y: -5 })
            bg5["normalTexture"] = TextureGenerator(renderer, stage, unit_normal_tex, bg5.texture.width, bg5.texture.height, bg5.tile_offset_x, bg5.tile_offset_y)
            stage.addChild(bg5);


            light.position.set(525, 1610);
            stage.addChild(new PIXI.lights.AmbientLight(null, 2));
            // stage.addChild(new PIXI.lights.DirectionalLight(null, 1, block1));
            stage.addChild(light);

            renderer.view.addEventListener('mousemove', function (e) {
                var rect = e.target["getBoundingClientRect"]();

                light.position.x = e.clientX - rect.left;
                light.position.y = e.clientY - rect.top;
            });

            renderer.view.addEventListener('click', function (e) {
                var rect = e.target["getBoundingClientRect"]();

                var clickLight = new PIXI.lights.PointLight(0xffffff);

                clickLight.position.x = e.clientX - rect.left;
                clickLight.position.y = e.clientY - rect.top;

                stage.addChild(clickLight);
                console.log("QAQ")
            });

            setInterval(function () {
                bg.tilePosition.x += 1;
                bg.tilePosition.y += 1;
                bg5.tilePosition.x += 1;
                bg5.tilePosition.y += 1;
            }, 1000 / 60)
            // setTimeout(function swap() {
            //     bg["normalTexture"] = unit_normal_tex;
            //     setTimeout(function () {
            //         bg["normalTexture"] = full_normal_tex;
            //         setTimeout(swap, 1000)
            //     }, 1000)
            // }, 1000)
        });
    stageManager.set(stage);
    // var wrapstage = new PIXI.Container();
    // wrapstage.addChild(stage)
} else if (location.hash === "#uvs") {
    var stage = new PIXI.Container();
    var loader = new PIXI.loaders.Loader();
    loader.add("snake_body", "/images/snake_body_test.jpg");
    loader.load();
    loader.once("complete", function (loader: PIXI.loaders.Loader, resource: PIXI.loaders.ResourceDictionary) {
        var base_x = 30;
        var base_y = 50;

        function popCGPoint() {
            return new PIXI.Point();
        };
        function pointDis(point_1: Point, point_2: Point) {
            return Math.sqrt(Math.pow(point_2.x - point_1.x, 2) + Math.pow(point_2.y - point_1.y, 2))
        };
        /**获取对应的边缘点 */
        function getSizePoints(pre_point, cur_point, nex_point, distance) {
            var base_direction_x = nex_point.x - pre_point.x;
            var base_direction_y = nex_point.y - pre_point.y;
            var rate_x_y = base_direction_x / base_direction_y;
            var rate_y_x = base_direction_y / base_direction_x;
            var res_direction_x = Math.sqrt(Math.pow(distance, 2) / (1 + Math.pow(rate_y_x, 2)));
            var res_direction_y = Math.sqrt(Math.pow(distance, 2) / (1 + Math.pow(rate_x_y, 2)));
            base_direction_x < 0 && (res_direction_x = - res_direction_x);
            base_direction_y < 0 && (res_direction_y = - res_direction_y);

            var left_size_point = popCGPoint();
            left_size_point.set(
                cur_point.x - res_direction_y
                , cur_point.y + res_direction_x
            );
            var right_size_point = popCGPoint();
            right_size_point.set(
                cur_point.x + res_direction_y
                , cur_point.y - res_direction_x
            );
            console.log(rate_x_y, (left_size_point.x - right_size_point.x) / (left_size_point.y - right_size_point.y));
            return [
                left_size_point,
                right_size_point,
            ];
        }
        interface Point {
            x: number,
            y: number
        }
        var points: Point[] = [{ "x": 8184.45834504748, "y": 8564.468236310155 }, { "x": 8194.266188209498, "y": 8569.479152543841 }, { "x": 8208.977952982372, "y": 8576.995526894369 }, { "x": 8228.648055873702, "y": 8584.441946368652 }, { "x": 8244.154682184413, "y": 8591.808417412944 }, { "x": 8259.661308495128, "y": 8599.174888457233 }, { "x": 8282.922649988608, "y": 8603.51974711398 }, { "x": 8297.634414731634, "y": 8611.036121464509 }, { "x": 8318.969055911071, "y": 8613.136788054751 }, { "x": 8335.013612947188, "y": 8618.758869655378 }, { "x": 8352.901282507184, "y": 8622.604689747124 }, { "x": 8370.78895206718, "y": 8626.450509838867 }, { "x": 8388.70030962136, "y": 8629.903315877022 }, { "x": 8403.412074364387, "y": 8637.419690227549 }, { "x": 8426.396465676735, "y": 8635.288464887715 }, { "x": 8445.166716877298, "y": 8636.67501945169 }, { "x": 8462.10041130763, "y": 8639.492142135277 }, { "x": 8479.034105737965, "y": 8642.309264818867 }, { "x": 8492.982345364155, "y": 8646.628247446473 }, { "x": 8505.82617167867, "y": 8644.31222344928 }, { "x": 8520.537936421697, "y": 8651.82859779981 }, { "x": 8531.515097158403, "y": 8654.279313142515 }, { "x": 8545.275370836789, "y": 8658.93463415156 }, { "x": 8559.035644515174, "y": 8663.589955160602 }, { "x": 8568.280784199993, "y": 8670.039606156977 }, { "x": 8576.76514207169, "y": 8675.003677386223 }, { "x": 8591.476906814714, "y": 8682.520051736752 }, { "x": 8600.848489246124, "y": 8695.769186036388 }, { "x": 8610.50580387906, "y": 8702.2882847285 }, { "x": 8620.163118511997, "y": 8708.807383420612 }, { "x": 8632.15953631691, "y": 8719.238720457128 }, { "x": 8634.874539549248, "y": 8730.384560507795 }, { "x": 8649.586304292276, "y": 8737.900934858322 }, { "x": 8648.048493939494, "y": 8749.936432169976 }, { "x": 8661.402585213465, "y": 8758.910287863499 }, { "x": 8674.756676487435, "y": 8767.88414355702 }, { "x": 8685.215609736377, "y": 8781.33847633166 }, { "x": 8696.269385049849, "y": 8792.460419335901 }, { "x": 8699.472007533139, "y": 8794.096668277363 }].map(point => new PIXI.Point(point.x, point.y));
        // var points = [{ "x": 10, "y": 10 }, { "x": 20, "y": 20 }, { "x": 30, "y": 10 }].map(point => new PIXI.Point(point.x, point.y));

        var base_spacing = 28.913918705046513;
        var snake_body_length = 571.8755078315735;
        var density = 38.91391870504651;

        var texture = resource["snake_body"].texture;
        var tex_width = texture.width;
        var tex_height = texture.height;

        /**一个位宽所需的点 */
        var unit_width_points_length = 1 + tex_width / base_spacing

        /**一单位位宽的uvs值 */
        var unit_width_rate = base_spacing / tex_width * (tex_height / density / 2);

        var pre_point = points[0];
        var cur_point = pre_point;
        var nex_point = points[1];
        var first_point_x = pre_point.x
        var first_point_y = pre_point.y
        points.forEach((point) => {
            point.x = point.x - first_point_x + base_x;
            point.y = point.y - first_point_y + base_y;
        });
        var points_bak = points.map(point => new PIXI.Point(point.x, point.y));

        var pathNode = document.createElementNS("http://www.w3.org/2000/svg", "path");
        pathNode.setAttribute("d", points.map((point, i) => {
            if (i === 0) {
                return "M " + point.x + " " + point.y + "C " + point.x + " " + point.y
            } else if (i < points.length - 1) {
                var pre_point = points[i - 1]
                var nex_point = points[i + 1]
                var a = getAnchors(pre_point.x, pre_point.y, point.x, point.y, nex_point.x, nex_point.y)
                return a.x1 + " " + a.y1 + " " + point.x + " " + point.y + " " + a.x2 + " " + a.y2
            } else {//最后一个点
                return point.x + " " + point.y + " " + point.x + " " + point.y
            }
        }).join(" "))
        points = [];
        for (var l = 0, total_path_length = pathNode.getTotalLength(), unit_l = base_spacing / 2 * total_path_length / snake_body_length, i = 0; l < total_path_length || (l = total_path_length); l += unit_l, i += 1) {
            points.push(pathNode.getPointAtLength(l))
            if (l >= total_path_length) {

                break
            }
        }
        var size_points = getSizePoints(pre_point, cur_point, nex_point, density);
        var left_size_point = size_points[0];
        var right_size_point = size_points[1];

        var vertices = [left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y];
        var uvs = [0, 0, 0, 1];
        var indices = [0, 1];
        var total_uvs = 0;
        for (var point_index = 1, len = points.length; point_index < len; point_index += 1) {
            cur_point = points[point_index];
            pre_point = points[point_index - 1] || cur_point;
            nex_point = points[point_index + 1] || cur_point;
            var pre_cur_dis = pointDis(pre_point, cur_point);
            var cur_uvs = unit_width_rate * pre_cur_dis / base_spacing;
            var _indice_len = indices.length
            total_uvs += cur_uvs;
            if (total_uvs >= 1) {
                //贴图溢出
                total_uvs = total_uvs % 1;

                if (total_uvs) {//在当前点前面插入一个临时点，来实现完整显示贴图
                    uvs.push(
                        1, 0, 1, 1
                        , 0, 0, 0, 1
                        , total_uvs, 0, total_uvs, 1
                        // , cur_uvs, 0, cur_uvs, 1
                    );
                    indices.push(
                        _indice_len, _indice_len + 1
                        , _indice_len + 2, _indice_len + 3
                        , _indice_len + 4, _indice_len + 5
                        // , _indice_len + 6, _indice_len + 7
                    );
                    //插入点(贴图末尾点)到前面点的距离
                    var pre_tex_dis = (cur_uvs - total_uvs) * base_spacing / unit_width_rate;
                    /**补帧点 */
                    var tex_point = popCGPoint();
                    tex_point.set(
                        pre_point.x + (cur_point.x - pre_point.x) * pre_tex_dis / pre_cur_dis,
                        pre_point.y + (cur_point.y - pre_point.y) * pre_tex_dis / pre_cur_dis
                    );
                    // 在pre和cur中间插入补帧点
                    points.splice(point_index, 0, tex_point);
                    point_index += 1;
                    len += 1;

                    var size_points = getSizePoints(pre_point, tex_point, cur_point, density);
                    var left_size_point = size_points[0];
                    var right_size_point = size_points[1];
                    vertices.push(
                        left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y
                        , left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y
                    );
                    var size_points = getSizePoints(tex_point, cur_point, nex_point, density);
                    var left_size_point = size_points[0];
                    var right_size_point = size_points[1];
                    vertices.push(
                        left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y
                    );
                } else {//===0
                    uvs.push(
                        1, 0, 1, 1
                        , 0, 0, 0, 1
                    );
                    indices.push(
                        _indice_len, _indice_len + 1
                        , _indice_len + 2, _indice_len + 3
                    );
                    var size_points = getSizePoints(pre_point, cur_point, nex_point, density);
                    var left_size_point = size_points[0];
                    var right_size_point = size_points[1];
                    vertices.push(
                        left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y
                        , left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y
                    )
                }
            } else {
                uvs.push(total_uvs, 0, total_uvs, 1)
                indices.push(
                    _indice_len, _indice_len + 1
                );
                var size_points = getSizePoints(pre_point, cur_point, nex_point, density);
                var left_size_point = size_points[0];
                var right_size_point = size_points[1];
                vertices.push(
                    left_size_point.x, left_size_point.y, right_size_point.x, right_size_point.y
                )
            }
        }


        var g1_line = new PIXI.Graphics();
        var g1_point = new PIXI.Graphics();
        stage.addChild(g1_line);
        stage.addChild(g1_point);

        g1_line.lineStyle(.5, 0xffc2c2);
        g1_point.lineStyle(.5, 0xffc2c2);
        g1_line.moveTo(points[0].x, points[0].y);

        for (var i = 0; i < points.length; i++) {
            if (i > 0) {
                g1_line.lineTo(points[i].x, points[i].y);
            }
            g1_point.beginFill(0xff0022);
            g1_point.drawCircle(points[i].x, points[i].y, 2);
            g1_point.endFill();
        };

        var g2_line = new PIXI.Graphics();
        var g2_point = new PIXI.Graphics();
        stage.addChild(g2_line);
        stage.addChild(g2_point);

        g2_line.lineStyle(.5, 0xc2c2ff);
        g2_point.lineStyle(.5, 0xc2c2ff);
        g2_line.moveTo(vertices[0], vertices[1]);

        for (var i = 0; i < vertices.length; i += 2) {
            if (i > 1) {
                g2_line.lineTo(vertices[i], vertices[i + 1]);
            }
            g1_point.beginFill(0x0022ff);
            g1_point.drawCircle(vertices[i], vertices[i + 1], 2);
            g1_point.endFill();
        };

        var g3_line = new PIXI.Graphics();
        var g3_point = new PIXI.Graphics();
        stage.addChild(g3_line);
        stage.addChild(g3_point);

        g3_line.lineStyle(.5, 0xc2c2ff);
        g3_point.lineStyle(.5, 0xc2c2ff);
        g3_line.moveTo(points_bak[0].x, points_bak[0].y);

        for (var i = 0; i < points_bak.length; i++) {
            if (i > 0) {
                g3_line.lineTo(points_bak[i].x, points_bak[i].y);
            }
            g3_point.beginFill(0x0022ff);
            g3_point.drawCircle(points_bak[i].x, points_bak[i].y, 2);
            g3_point.endFill();
        };

        var mesh = new PIXI.mesh.Mesh(texture);
        stage.addChild(mesh);
        setTimeout(function () {
            mesh.vertices = new Float32Array(vertices)
            mesh.uvs = new Float32Array(uvs)
            mesh.indices = new Uint16Array(indices)
            mesh.dirty = true;
            mesh.alpha = 0.5;
        }, 0)

        stage.scale.set(2.5, 2.5)

    });
    stageManager.set(stage);
} else {
    stageManager.set(l_stage);
}

function animate() {
    renderer.render(stageManager.get());
    requestAnimationFrame(animate);
}

animate();